﻿using DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FrmMain
{
    public partial class FrmMain : Form
    {
        string Name { get; set; }
        public FrmMain()
        {
            InitializeComponent();
        }

        public FrmMain(string strName)
        {                         
            InitializeComponent();
            Name = strName;
            InitData();
        }

        private void InitData()
        {
            if (grdData.Rows.Count-1 > 0)
            {
                grdData.Rows.Clear();
            }
            string strSql = "select * from Students";
            DataSet ds = DBHelp.GetDataSet(strSql);  

            foreach (System.Data.DataRow date in ds.Tables[0].Rows)
            {
                DataGridViewRow newRow = new DataGridViewRow();
                newRow.CreateCells(grdData);

                newRow.Cells[0].Value = date[1].ToString();
                newRow.Cells[1].Value = date[2].ToString();
                newRow.Cells[2].Value = date[3].ToString();
                newRow.Cells[3].Value = date[4].ToString();
                grdData.Rows.Add(newRow);
            }
        }

        private void cmdUpdate_Click(object sender, EventArgs e)
        {
            var row = grdData.SelectedRows[0];  

            string strName = Convert.ToString(row.Cells[0].Value);
            int intAge = Convert.ToInt32(row.Cells[1].Value);
            int intCore = Convert.ToInt32(row.Cells[2].Value);
            int intClass = Convert.ToInt32(row.Cells[3].Value);


            string strSql = " update Students set [Age]='" + intAge +
                "',[Score]='" + intCore + "',[ClassNum] = '" + intClass +
                "' where Name = '" + strName + "'";
            int intRe =  DBHelp.ExecuteNonQuery(strSql);
            if(intRe >0)
            {
                MessageBox.Show("修改成功！");
                grdData.DataSource = null;
                

                InitData();
                return;
            }
            else
            {
                MessageBox.Show("修改失败！");
            }

        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            var row = grdData.SelectedRows[0];
            string strName = row.Cells[0].Value.ToString();

            string cmdText = "delete from Students where Name='" + strName + "'";
            int intRe = DBHelp.ExecuteNonQuery(cmdText);
            if(intRe>0)
            {
                MessageBox.Show("删除成功！");
                grdData.DataSource = null;
                InitData();
                return;
            }
            else
            {
                MessageBox.Show("删除失败！");
            }
        }
    }
}
